package com.yebxxx.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component  //标识为一个类
public class JwtTokenUtil {
public  static  final String CLAIM_KEY_USERNAME="sub";   //用户名
    public  static  final String CLAIM_KEY_CREATED="created"; //创建时间
    @Value("${jwt.secret}")
    private  String secret;  //密钥
    @Value("${jwt.expiration}")
    private  Long expiration; //失效时间

    //根据用户信息生成Token

    /**
     * 根据用户的个人信息
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims=new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    /**
     * 从token获取登录用户名
     * @param   token
     * @return
     */
public String getUsernameFromToken(String token){
    String username;
    try {
        Claims claims= getClaimsFromToken(token);
        username=claims.getSubject();
    }catch (Exception e){
        username=null;
    }
    return  username;
}
    //从token获取荷载
    private Claims getClaimsFromToken(String token) {
        Claims claims=null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  claims;
    }

    /**
     * 验证token是否有效
     * @param token
     * @param userDetails
     * @return
     */
    public  boolean validateToken(String token,UserDetails userDetails){
    String username=getUsernameFromToken(token);
    return  username.equals(userDetails.getUsername()) &&! isTokenExpired(token);
}

    /**
     * 判断token是否失效
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
      Date expireDate= getExpiredDateFromToken(token);
      return  expireDate.before(new Date());
    }

    /**
     * 从token中获取失效时间
     * @param token
     * @return
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 判断token是否失效
     * @param token
     * @return
     */
    public  boolean canRefresh(String token){
        return  !isTokenExpired(token);
}

    /**
     * 刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token){
    Claims claims = getClaimsFromToken(token);
    claims.put(CLAIM_KEY_CREATED,new Date());
    return  generateToken(claims);
}

    //根据荷载生成Token
    private  String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims) //荷载
                .setExpiration(generateExceptionDate()) //失效时间
                .signWith(SignatureAlgorithm.HS512,secret) //签名  密钥
                .compact();
    }
    //生成token失效时间
    private Date generateExceptionDate() {
     return  new Date(System.currentTimeMillis()+expiration*1000);
    }
}
